// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import App from './App';
import router from './router';
import store from './store';
import ViewUI from 'view-design';
import VueI18n from 'vue-i18n';
import Route from 'vue-router';
import 'view-design/dist/styles/iview.css'
import axios from '@/libs/axios.js';
import global_ from './api/index';
import qs from 'qs';
// import hljs from 'highlight.js';
import cookieUse from '@/libs/cookie.js';
import VueQuillEditor from 'vue-quill-editor';
import enLocale from 'view-design/dist/locale/en-US';
import zhLocale from 'view-design/dist/locale/zh-CN';
import enLocaleElement from 'element-ui/lib/locale/lang/en';
import zhLocaleElement from 'element-ui/lib/locale/lang/zh-CN';
import cn from '@/lang/zh-CN.js';
import us from '@/lang/en-US.js';
import mavonEditor from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
import 'xe-utils';
import VXETable from 'vxe-table';
import 'vxe-table/lib/style.css';
import SuperFlow from './libs/packages/index.vue';
import xss from 'xss';
import { getMessageText } from '@/libs/utils';
import watermark from '../static/js/watermark.js';
import TableList from '@/components/common/table-list';
import ScriptData from '@/components/script-data';
import WarningTip from '@/components/common/warning-tip';
import NoData from '@/components/common/no-data';
import ColPage from '@/components/common/page';
import MenuPage from '@/components/common/page/menu-page.vue';
import DrawerPage from '@/components/common/page/drawer-page.vue'
import SearchTable from '@/components/SearchTable/SearchTable';
import MyPage from '@/components/common/Pagination';
import pageTitleMixin from './mixin/pageTitle';

// import PageTitle from '@/components/common/page-title';
// element-ui的Cascader组件支持多选功能，特意引入并在知识赛赛题字段选择、试卷自动生成页面使用
import 'element-ui/lib/theme-chalk/index.css';
import { Cascader,Switch } from 'element-ui';
import { getMenuList, dealParentViewPage } from './router/menu_config';
import {
    vulnerabilityLevelEscape,
    vulnerabilityDisposalPriorityEscape
} from '@/view/testPlatform/vulnerability/logic/vulnerabilityLogic'
import './micro';
// import { scrollBoard, decoration9} from '@jiaminghi/data-view'
// 引入组件
Vue.use(Cascader);
Vue.use(Switch);
// Vue.use(scrollBoard)
// Vue.use(decoration9)
//import moment from 'moment';

// import 'vue-super-flow/lib/index.css'
//按需引入echart，引入基本模板
// let echarts = require('echarts/lib/echarts');
// // 引入饼状图组件
// require('echarts/lib/chart/pie');
// require('echarts/lib/chart/bar');
// require('echarts/lib/chart/line');
// // 引入提示框和title组件，图例
// require('echarts/lib/component/tooltip');
// require('echarts/lib/component/title');
// require('echarts/lib/component/legend');
// require('echarts/lib/component/dataZoom');
// require('echarts/lib/component/visualMap');
// require('echarts/lib/component/legendScroll');

import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
const originalPush = Route.prototype.push;
/*Route.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}*/

// 样式重置
// import '@/styles/theme.css';
import '@/styles/base.css';
import '@/styles/common.css';
import '@/styles/iview-reset.css';

Vue.config.productionTip = false;

Vue.use(VXETable);
Vue.use(ViewUI, {
    i18n: function (path, options) {
        let value = i18n.t(path, options);
        if(value==='跳至') return '前往'
        if (value !== null && value !== undefined) {
            return value;
        }
        return '';
    },
});


Vue.prototype.hideCompet = true
Vue.prototype.$ConfigurationParameter = {
    VULNERABILITY_LEVEL_OPTIONS: {
        '0': '超危',
        '1': '高危',
        '2': '中危',
        '3': '低危'
    },
    VULNERABILITY_DISPOSAL_PRIORITY_OPTIONS: {
        '1': '高优先级',
        '2': '中高优先级',
        '3': '中优先级',
        '4': '中低优先级',
        '5': '低优先级'
    }
}
Vue.prototype.$CodeEscape = {
    vulnerabilityLevelEscape: vulnerabilityLevelEscape,
    vulnerabilityDisposalPriorityEscape: vulnerabilityDisposalPriorityEscape
}
//Input MaxLength 初始化为500
ViewUI.Input.props.maxlength.default = 500;
//InputNumber
ViewUI.InputNumber.props.activeChange.default = false;
//Cascader搜索不区分大小写
ViewUI.Cascader.computed.querySelections = ((cur) => {
    let selections = [];
    function getSelections (arr, label, value) {
        for (let i = 0; i < arr.length; i++) {
            let item = arr[i];
            item.__label = label ? label + ' / ' + item.label : item.label;
            item.__value = value ? [...value, item.value] : [item.value];

            if (item.children && item.children.length) {
                getSelections(item.children, item.__label, item.__value);
                delete item.__label;
                delete item.__value;
            } else {
                selections.push({
                    label: item.__label,
                    value: item.__value,
                    display: item.__label,
                    item: item,
                    disabled: !!item.disabled
                });
            }
        }
    }
    getSelections(cur.data);
    selections = selections.filter(item => {
        return item.label ? item.label.toLowerCase().indexOf(cur.query.toLowerCase()) > -1 : false;
    }).map(item => {
        if(item.display){
            item.display = item.display.replace(new RegExp(cur.query, 'g'), `<span>${cur.query}</span>`);
        }
        return item;
    });
    return selections;
})
//解决文件没上传完，clearFiles后报错问题
ViewUI.Upload.methods.handleProgress = function(e, file) {
    var _file = this.getFile(file);
    if(!_file){
        // console.log(e)
        // e.currentTarget.abort()
        return
    }else{
        this.onProgress(e, _file, this.fileList);
        _file.percentage = e.percent || 0;
    }
}
//解决文件没上传完，clearFiles后报错问题
ViewUI.Upload.methods.handleError = function(e, file) {
    var _file = this.getFile(file);
    if(!_file){
        // console.log(e)
        // e.currentTarget.abort()
        return
    }else{
        var fileList = this.fileList;
        _file.status = 'fail';
        fileList.splice(fileList.indexOf(_file), 1);
        this.onError(err, response, file);
    }
}
// 统一系统中的Page,提供[10,20选择]
// console.log(ViewUI.Page)
// ViewUI.Page.props.pageSizeOpts.default= () => {
//     return [10,20]
// }
// ViewUI.Page.props.showSizer.default = true;
// ViewUI.Page.props.showElevator.default = true;

Vue.use(qs);
Vue.use(VueI18n);
Vue.locale = () => {};
Vue.use(ViewUI, { enLocale });
Vue.use(ViewUI, VueQuillEditor);
//Vue.prototype.$echarts = echarts;
Vue.prototype.axios = axios;
Vue.prototype.baseURL = global_;
Vue.prototype.$Qs = qs;
Vue.prototype.xss = xss;
//Vue.prototype.$Moment = moment;
Vue.prototype.$Message.config({
    duration: 3,
});
Vue.directive('imgerror', {
    inserted(el, bindings) {
        el.onerror = function() {
            el.src = bindings.value
        }
    }
})
Vue.component('TableList', TableList);
Vue.component('WarningTip', WarningTip);
Vue.component('ScriptData', ScriptData);
Vue.component('ColPage', ColPage);
Vue.component('MenuPage',MenuPage);
Vue.component('DrawerPage',DrawerPage);
Vue.component('NoData', NoData);
Vue.component('SearchTable',SearchTable)
Vue.component('MyPage',MyPage)
Vue.mixin(pageTitleMixin);
let messageFnNames = ['info', 'success', 'warning', 'error', 'loading'];
messageFnNames.forEach((fnName) => {
    Vue.prototype.$Message[`_${fnName}`] = Vue.prototype.$Message[fnName];
    Vue.prototype.$Message[fnName] = (config) => {
        let data = {};
        if (typeof config === 'string') {
            data.content = getMessageText(config);
        } else {
            data = Object.assign({}, config);
            data.content = getMessageText(data.content);
        }
        if(!data.content){
            return
        }
        return Vue.prototype.$Message[`_${fnName}`](data);
    };
});
Vue.use(mavonEditor);
Vue.use(SuperFlow);
// Vue.directive('highlight', function (el) {
//     let blocks = el.querySelectorAll('pre code');
//     blocks.forEach((block) => {
//         hljs.highlightBlock(block);
//     });
// });
let lang = 'zh' //cookieUse.getCookie('desig-lang') || 'zh';
const messages = {
    zh: Object.assign(cn, zhLocale, enLocaleElement),
    en: Object.assign(us, enLocale, zhLocaleElement),
};
// 设置参数，创建 Vuei18n 的实例。
const i18n = new VueI18n({
    locale: lang, // set locale
    messages, // set locale messages
});
// 是否需要请求菜单数据
let needOpMenu = true;
// 是否需要请求用户信息，刷新页面或刚登陆时需要获取，不需要每次切换路由都获取
let needReqUser = true;

router.beforeEach(async (to, from, next) => {
    dealParentViewPage(to, from, next);
    let loginPage = sessionStorage.getItem('loginPage') || 'login';
    // 判断该路由是否需要登录权限
    if (to.meta.requireAuth !== false) {
        if (cookieUse.getCookie('desig-token') && cookieUse.getCookie('desig-token') !== '') {
            // sessionStorage.setItem('desig-token',cookieUse.getCookie('desig-token'))
            // sessionStorage.setItem('desig-current-path',to.name)
            //组件渲染之前 获取用户数据,vuex存储
            if (needReqUser && to.name != 'login' && to.meta.login !== true) {
                let { code, data: userInfo, message } = await store.dispatch('user/getUserInfo');
                // 水印，不知道要不要，需要的话放开就行
                // watermark.init({ watermark_txt: userInfo.userName });
                if (code == 1) {
                    needReqUser = false;
                    if (userInfo.initialPassword && from.name == 'login') {
                        ViewUI.Notice.info({
                            title: '提示：',
                            desc: '请更改初始密码!',
                            duration: 5,
                        });
                    }
                }else{
                    return
                }
            }
            if (to.name != 'login' && needOpMenu && to.meta.login !== true) {
                needOpMenu = false;
                let isSuccess = await getMenuList(to, next);
                needOpMenu = isSuccess ? false : true;
                if(!isSuccess){
                    next({
                        path: `/${loginPage}`,
                    });
                    store.dispatch('login/verification')
                } else {
                    store.dispatch('common/getIsDistributed')
                }
            } else{
                if (to.name == 'login' || to.meta.login === true) {
                    needOpMenu = true;
                    needReqUser = true;
                    if(loginPage !== 'login' && to.name == 'login' && from.name && !from.meta.login){
                        next({
                            path: `/${loginPage}`,
                        });
                    }
                    // 避免报错，需要水印的时候才放开
                    // watermark.remove({ watermark_txt: '' });
                }
                next()
            }
        } else {
            needOpMenu = true;
            needReqUser = true;
            next({
                path: `/${loginPage}`,
            });
        }
    } else {
        if (to.name != 'login' && needOpMenu && to.meta.login !== true) {
            needOpMenu = false;
            let isSuccess = await getMenuList(to, next);
            needOpMenu = isSuccess ? false : true;
            if(!isSuccess){
                next({
                    path: `/${loginPage}`,
                });
                store.dispatch('login/verification')
            } else {
                store.dispatch('common/getIsDistributed')
            }
        } else {
            if (to.name == 'login' || to.meta.login === true) {
                needOpMenu = true;
                needReqUser = true;
                if(loginPage !== 'login' && to.name == 'login' && !from.meta.login){
                    next({
                        path: `/${loginPage}`,
                    });
                }
                // 避免报错，需要水印的时候才放开
                // watermark.remove({ watermark_txt: '' });
            }
            next();
        }
    }

    if (store.state.user.NewNameList.length > 0) {
        if (to.name !== 'main' && !store.state.user.NewNameList.includes(to.name)) {
            next({
                path: '/homer',
            });
        }
    }
});
/* eslint-disable no-new */
new Vue({
    el: '#indexapp',
    router,
    i18n,
    store,
    render: function (h) { return h(App) }
    // components: { App },
    // template: '<App/>',
});



// 由于微服务的原因，window.open ,打开的是基座的 链接所有要重写open 方法
// let href = location.origin+"/training/#/examReport?id="+data.id
// 用openTrain 不要影响基座的open方法

// 重写 window.openTrain 方法
window.openTrain = function(url, target, features) {
    // if(window.microApp && (url+'').startsWith('#/')){ // 1.如果是 子服务的话需要的跳转方式
    //     let newurl = location.origin+`/training/${url}`
    //     // console.log('重写了一些路由',newurl)
    //     return window.open(newurl, target, features);
    // }

    // 如果不是#/ 开头的 正常跳转
    return window.open(url, target, features);
};
window.openLogin = function(router) {
    // if(window.microApp){ // 2.如果是 子服务的话需要的跳转方式
    //     window.open('#/login','_self')
    // }else {
    router.push({ //
        path:'/login',
    })
    //}
};

